﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System;

namespace UnityEngine.Extension
{
    public static class GameObjectExtension
    {
        public static GameObject InstantiateInHierarchy(this GameObject source)
        {
            GameObject instanceObj = (GameObject)GameObject.Instantiate(source);
            //instanceObj.transform.SetParent(source.transform.parent);
            instanceObj.transform.parent = source.transform.parent;
            instanceObj.transform.localScale = source.transform.localScale;
            return instanceObj;
        }
        public static GameObject GetNonActiveChild(this GameObject source)
        {
            GameObject result = null;
            foreach(Transform child in source.transform)
            {
                if(!child.gameObject.activeSelf)
                {
                    result = child.gameObject;
                    result.SetActive(true);
                    break;
                }
            }
            return result;
        }

        public static void ForEachComponent<T>(this GameObject source, Action<T> callBack) where T : Component
        {
            T[] components = source.GetComponents<T>();
            foreach (T component in components)
                callBack(component);
        }

        public static void ForEachChildComponent<T>(this GameObject source, Action<T> callBack) where T : Component
        {
            T[] components = source.GetComponentsInChildren<T>();
            foreach (T component in components)
                callBack(component);
        }

        public static void ForEachChild(this GameObject source, Action<GameObject> callBack)
        {
            foreach (Transform child in source.transform)
                callBack(child.gameObject);
        }

        public static void SetChildrenActive(this GameObject source, bool value)
        {
            source.ForEachChild(c => c.SetActive(value));
        }

        public static void DestroyChilds(this Transform source)
        {
            foreach (Transform child in source)
                GameObject.Destroy(child.gameObject);
        }
    }
}